<template>
<div style="width:100%">
    <el-form ref="ruleFormRef" :model="ruleForm">
      <el-input 
        v-model="ruleForm.textarea1"  style="width: 800px" :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea" @paste.native="pasteInfo($event)"  clearable
                placeholder="请将Excel表格中的内容复制粘贴到这里"  />
       <!-- <el-button type="Default" :icon="View" @click="printDetail" style="margin-left:20px">JS打印预览</el-button> -->
        <el-button @click="resetForm"  style="margin-left:40px">清空</el-button>
        <el-button type="primary" :icon="Printer" @click="submitPrint" style="margin-left:40px">浏览器打印</el-button>
        <el-button type="success" :icon="Printer" @click="print2List">直接打印</el-button>
    </el-form>
        <div >
          <el-table :data="tableData" id="print-div1" >
            <el-table-column prop="sizeName" label="尺码" width="180" />
             <el-table-column prop="sourceData" label="原始数据" width="180"  />
            <el-table-column prop="total" label="尺码总数" width="180" >
           
            </el-table-column>
            <el-table-column prop="num" label="号码*数量" >
                <template #default="scope">
                    <span v-for="item in scope.row.numList" :key="item" style="margin-left:10px; font-weight:bold"> 【{{item.sizeNum}} * {{item.count}}】</span>
                </template>
            </el-table-column>
          </el-table>

        </div>
          <start-preview ref="preview" />
    </div>
</template>
<script lang="ts" setup>
import { ref ,onMounted,reactive,getCurrentInstance} from 'vue'
import { hiprint, defaultElementTypeProvider } from "vue-plugin-hiprint";
import { Delete, Edit, Search, Share, Upload,View,Printer } from '@element-plus/icons-vue'
import startPreview from "../../components/preview.vue";

import type { FormInstance, FormRules } from 'element-plus'

import { newHiprintPrintTemplate } from "../../utils/template-helper";

import template from "./template";


const TEMPLATE_KEY = getCurrentInstance().type.name; // 存储模板对象的 key

hiprint.init();

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive({
  textarea1: '',
})


const textarea1 = ref('')
const textarea2 = ref('')

const preview = ref(null);
let hiprintTemplate ;
const templateRef = ref(template);
let rowsInfo;
let currentRowIndex= 0 ;
let currentColumnIndex= 0;
let  temp={};
let  emptyObj= {
        sizeName:'',
        num:'',
      };

const  tableData = ref([ 
      ]);
let  columns=[
    {
      key:'sizeName',
      align:'center'
    },
    {
      key:'num',
      align:'center'
    },
  ];

onMounted(() => {
    hiprintTemplate = newHiprintPrintTemplate(TEMPLATE_KEY, {
    template: templateRef.value, // 模板json(object)
  });


});


const resetForm = () => {
  ruleForm.textarea1='';
}

const getHtmlList = () => {
  //hiprintTemplate.rotatePaper();
  let html = hiprintTemplate.getHtml({table:tableData.value});
  console.log(html);
  preview.value.showModal(html);
};

 // eslint-disable-next-line no-undef
const submitPrint =()=>{

  // 参数: 打印时设置 左偏移量，上偏移量
  let options = { leftOffset: 0, topOffset: 0 };
  // 扩展
  let ext = {
    callback: () => {
      console.log("浏览器打印窗口已打开");
    },
    styleHandler: () => {
      // 重写 文本 打印样式
     // return "<style>.hiprint-printElement-text{color:red !important;}</style>";
    },
  };

  // 调用浏览器打印
  hiprintTemplate.print({table:tableData.value});

}

const print2List = () => {
  if (hiprint.hiwebSocket.opened) {
    hiprintTemplate.print2({table:tableData.value});
  } else {
    alert("请先连接客户端(刷新网页), 然后再点击「直接打印」");
  }
};

// const printDetail = ()=>{
//     const style = '@page {margin:0 0mm;  maxWidth:2000px} ' ;        
//     print({
//       printable: 'print-div',// 标签元素id
//       type: 'html',
//       header: '',
//       targetStyles: ['*'],
//       style: style
//     });

// }

const  pasteInfo =(e)=> {
    tableData.value=[];
    try {
      var data = null;
      var clipboardData = e.clipboardData; // IE
      if (!clipboardData) {
        //chrome
        clipboardData = e.originalEvent.clipboardData;
      }
      //复制过来的内容
      data = clipboardData.getData("Text");
      console.log(data)
      //首先对源头进行解析
      var rowStrArray = data.split("\n");//拆成很多行
      console.log(rowStrArray,'rowStrArray')
      rowsInfo = [];
      for (var i = 0; i < rowStrArray.length-1; i++) {
        var row = [];
        var tdStrArray = rowStrArray[i].split("\t");//按列拆分
        for (var j = 0; j < tdStrArray.length; j++) {
          row.push(tdStrArray[j]);
        }
        rowsInfo.push(row);
      }
      console.log(rowsInfo,'rowInfo');
      var totalNum=0;
      for (var j = 0; j < rowsInfo.length; j++) {
        
        temp = {sizeName:'',num:'',numList:[],total:0,numSize:'',sourceData:[]};

        let num = 0
        // let numFlag = 0 //限制从第几列开始粘贴(如果全部列都可以粘贴,就是从0列粘贴,numFlag=0)
        temp["sizeName"] = rowsInfo[j][0];
        var tempList = [];
        var sourceData = [];
        var numSize ='';
        for(var k=1;k<rowsInfo[j].length;k++){
            var tempRow = rowsInfo[j][k];
            tempRow = tempRow.replace(/\ +/g,"");
            tempRow = tempRow.replace(/[ ]/g,"");
            tempRow = tempRow.replace(/[\r\n]/g,"");
            if(tempRow!=''){
              var arr = tempRow.split(",");
                console.log(arr,"arr");
              for(var index_2=0; index_2<arr.length;index_2++){
                console.log(arr[index_2],"temp1");
                if(arr[index_2]!=''){
                    tempList.push(arr[index_2]);
                }
              }

              sourceData.push(tempRow);
            }
        }
        
        console.log(tempList,"tempList");
        var obj = {};
        for (var l=0;l<tempList.length;l++) {
            if (obj[tempList[l]]) {
              obj[tempList[l]]++;
            } else {
              obj[tempList[l]] = 1;
            }
        }
        var numList =[];
        var  total =0;
        var sizeNum='';
        var tempIndex=0;
        for (let key in obj) {
          total += obj[key];
          numList.push({
            sizeNum: key,
            count: obj[key],
          });
          tempIndex++;
          sizeNum = sizeNum +' 【'+key+ '*'+ obj[key] +'】 ';
          if(tempIndex%8==0){
            sizeNum = sizeNum + ' <br /> ';
          }
          
        }
        totalNum = totalNum + total;
        temp["numList"]= numList;
        temp["total"] = total;
        temp["sizeNum"]=sizeNum;
        temp["sourceData"] =sourceData;
        tableData.value.push(temp);
      }

      temp = {sizeName:'总计',num:'',numList:[],total:totalNum,numSize:'',sourceData:[]};
      tableData.value.push(temp);
      console.log(tableData,"tableData");

    } catch(err) {

    }
}

</script>

<style>
.page-a4 {
  /** A4纸: 210mm * 297mm */
  width: 297mm;
  margin: 10mm;
}

.print-page {
  width: 290mm;
  height: 210mm;
  margin: 0 auto;
  text-align: center;
  margin-bottom: 14mm;
  border: 1px solid #bbb;
}

/*去除页脚*/
@page {
  size: auto;
  margin: 0;
}

.wrapper {
    height: 100vh;
    overflow: hidden;
}
.content-box {
    position: absolute;
    left: 200px;
    right: 0;
    top: 70px;
    bottom: 0;
    padding-bottom: 30px;
    -webkit-transition: left 0.3s ease-in-out;
    transition: left 0.3s ease-in-out;
    background: #eef0fc;
    overflow: hidden;
}

.content {
    width: auto;
    height: 100%;
    padding: 20px;
    overflow-y: scroll;
    box-sizing: border-box;
}

.content::-webkit-scrollbar {
    width: 0;
}

.content-collapse {
    left: 65px;

   
   
}
  
</style>
